//
//  Extensions.swift
//  MyDiary2025
//
//  Created by 罗万能 on 2025/6/25.
//

import Foundation
import SwiftUI
import AVKit

import SwiftUI
import UIKit
import CoreLocation


import SwiftUI

extension Color: Codable {
    private struct ColorRGBA: Codable {
        let red: Double
        let green: Double
        let blue: Double
        let opacity: Double
    }
    
    public init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        let rgba = try container.decode(ColorRGBA.self)
        
        // 从 RGBA 值创建 Color
        self.init(
            red: rgba.red,
            green: rgba.green,
            blue: rgba.blue,
            opacity: rgba.opacity
        )
    }
    
    public func encode(to encoder: Encoder) throws {
        // 从 Color 提取 RGBA 值
        var r: CGFloat = 0
        var g: CGFloat = 0
        var b: CGFloat = 0
        var o: CGFloat = 0
        
        // 转换为 UIColor (UIKit) 或 NSColor (AppKit)
        #if canImport(UIKit)
        let uiColor = UIColor(self)
        uiColor.getRed(&r, green: &g, blue: &b, alpha: &o)
        #elseif canImport(AppKit)
        let nsColor = NSColor(self)
        let rgbColor = nsColor.usingColorSpace(.deviceRGB)!
        rgbColor.getRed(&r, green: &g, blue: &b, alpha: &o)
        #endif
        
        let rgba = ColorRGBA(
            red: Double(r),
            green: Double(g),
            blue: Double(b),
            opacity: Double(o)
        )
        
        var container = encoder.singleValueContainer()
        try container.encode(rgba)
    }
}
extension Date {
    var viewDate: String {
        let calendar = Calendar.current
        let components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .weekday], from: self)
        let now = Date()
        let interval = now.timeIntervalSince(self)
        
        // 格式化小时和分钟（确保分钟两位数）
        let hour = components.hour ?? 0
        let minute = components.minute ?? 0
        let timeString = String(format: "%d:%02d", hour, minute)
        
        if interval < 60 * 60 * 24 {
            return timeString // 使用格式化后的时间
        } else if interval < 60 * 60 * 24 * 2 {
            return "昨日"
        } else if interval < 60 * 60 * 24 * 3 {
            return "前日"
        } else if interval < 60 * 60 * 24 * 7 {
            let weekday = components.weekday ?? 0
            let weekdayNames = ["日", "一", "二", "三", "四", "五", "六"]
            return "星期\(weekdayNames[min(weekday, 6)])"
        } else if interval < 60 * 60 * 24 * 30 {
            return "\(components.day ?? 0)日"
        } else if interval < 60 * 60 * 24 * 365 {
            return "\(components.month ?? 0)月"
        }
        return "\(components.year ?? 0)年"
    }
}

extension Image: @retroactive Identifiable{
    
    public var id: UUID {
        return UUID()
    }
}

extension AVPlayer: @retroactive Identifiable{
    public var id: UUID{
        return UUID()
    }
}
